<?php

namespace app\model;

use think\Model;
use think\model\relation\HasOne;

class UserChangeScore extends Model
{
    public function getPage(): array
    {
        $param = request()->param();
        $page = $param["page"] ?? 1;
        $limit = $param["limit"] ?? 50;
        $where = $this->with(["user", "changeUser"])->when(!empty($param['uid']), function ($query) use ($param) {
            $query->where("uid", $param['uid']);
        })->when(!empty($param['change_uid']), function ($query) use ($param) {
            $query->where("change_uid", $param['change_uid']);
        })->when(!empty($param['create_time']), function ($query) use ($param) {
            $query->whereBetween("create_time", [$param['create_time'][0] . " 00:00:00", $param['create_time'][1] . " 23:59:59"]);
        })->when(!empty($param['change_code']), function ($query) use ($param) {
            $query->where("change_code", $param['change_code']);
        })->when(!empty($param['mobile']), function ($query) use ($param) {
            $uid = User::where("mobile", $param['mobile'])->column("id");
            $query->whereIn("change_uid", $uid);
        })->when(!empty($param['user']), function ($query) use ($param) {
            $uid = User::where("mobile", $param['user'])->column("id");
            $query->whereIn("uid", $uid);
        });
        $data = $where->order("create_time", "desc")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
        $chat = $where->sum("number");
        return ['lst' => array_map(function ($item) {
            $item['number'] = (float)bcdiv($item['number'], 100, 2);
            return $item;
        }, $data['data']), 'last_page' => $data['last_page'], 'total' => $data['total'], 'chat' => bcdiv($chat, 100, 2)];
    }


    public function user(): HasOne
    {
        return $this->hasOne(User::class, "id", "uid");
    }

    public function changeUser(): HasOne
    {
        return $this->hasOne(User::class, "id", "change_uid");
    }

    public function download(): array
    {
        $data = $this->getPage();
        $result = array_map(function ($item) {
            return [
                $item['change_code'],
                $item['user']['username'],
                $item['changeUser']['username'],
                $item['number'],
                $item['create_time'],
            ];
        }, $data['lst']);
        $totalPage = $data['last_page'];
        $header = ["订单号", "转让人", "受让人", "转让积分", "转让时间"];
        $title = ["转让记录"];
        $file = "转让记录";
        return compact("result", "header", "title", "totalPage", "file");
    }
}
